package top.infopub.mgr.cap.web;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.infopub.dto.cap.FinReimDto;
import top.infopub.enums.hr.PostGroupEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.cap.jsonvo.FinReimJsonVo;
import top.infopub.mgr.cap.service.CapProcessManageService;
import top.infopub.mgr.cap.service.FinanceReimbursementService;
import top.infopub.mgr.cap.vo.FinanceReimbursementVo;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.mkt.service.MarketManageService;
import top.infopub.model.cap.FinanceReimbursement;
import top.infopub.model.hr.OrgInfo;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Warking
 * @Date 2021/5/24 14:30
 * @Version 1.0  融资还款
 */
@Controller
@RequestMapping("/financeReimbursement")
public class FinanceReimbursementController extends GenericFlowController {


    @Autowired
    private FinanceReimbursementService financeReimbursementService;

    @Autowired
    private MarketManageService marketManageService;

    @Autowired
    private CapProcessManageService capProcessManageService;

    /**
     * 融资还款列表
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        //获取登录人员信息
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        //查询区域公司列表
        List<OrgInfo> orgInfoList = marketManageService.queryOrgInfoByAuthUserId(vo);
        request.setAttribute("orgInfoList", orgInfoList);
        return "cap/lay-financeReimbursement-list";
    }

    /*融资还款列表接口*/
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<FinanceReimbursement> queryDataByCondition(FinanceReimbursementVo financeReimbursementVo, ParamPage paramPage) throws ParseException {
        Page<FinanceReimbursement> page = new Page();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = financeReimbursementService.selectPage(page,financeReimbursementVo );
        return RspVo.getSuccessResponse(page.getTotal(),page.getResult());
    }

    /**
     * 根据id查询融资付款详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 融资放款Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public String toDealOrDetail(HttpServletRequest request, String id, String proCode) {
        request.setAttribute("id", id);
        FinanceReimbursement finReim = financeReimbursementService.selectByPrimaryKey(id);
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("auditTabFlag", "0");//登录人和审批人一致使用该字段是否显示审核信息
        request.setAttribute("finFlag", "0");//指定财务人员进入审批页面必须填写财务信息
        if (finReim != null) {
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), finReim.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), finReim.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(finReim.getProcessId()) && finReim.getProcessId().length() > 10) {
                request.setAttribute("processId", finReim.getProcessId());
                String auditTabFlag = capProcessManageService.checkShowAuditTab(finReim.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), finReim.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                //查询指定财务节点人员ID
                List<String> finUserIdList = capProcessManageService.queryFinanceUserIdByProcessId(finReim.getProcessId(), "-1", PostGroupEnum.FINANCE.getCode());
                if (finUserIdList != null && finUserIdList.size() > 0) {
                    for (String finUserId : finUserIdList) {
                        if (StringUtils.isBlank(finUserId)) continue;
                        if (StringUtils.equals(vo.getId(), finUserId)) {
                            //当前待审批节点=当前登录人，需要编辑财务信息提交
                            request.setAttribute("finFlag", "1");//指定财务人员进入审批页面必须填写财务信息
                        }
                    }
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
        }
        request.setAttribute("proCode", proCode);
        return "cap/lay-FinancingRepayment-detail";
    }

    @RequestMapping("/queryDetail")
    @ResponseBody
    public RspVo queryDetail(String id) {
        FinReimJsonVo finReimJson = financeReimbursementService.queryDetailById(id);
        return RspVo.getSuccessResponse(finReimJson);
    }

    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String processId, String status, String auditMsg, FinanceReimbursement finReim) {
        //融资付息审批
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        List<String> finUserIdList = capProcessManageService.queryFinanceUserIdByProcessId(processId, "-1", PostGroupEnum.FINANCE.getCode());
        if (finUserIdList != null && finUserIdList.size() > 0) {
            for (String finUserId : finUserIdList) {
                if (StringUtils.isBlank(finUserId)) continue;
                if (StringUtils.equals(vo.getId(), finUserId)) {
                    //当前待审批节点=当前登录人，需要编辑财务信息提交
                    if (finReim == null || finReim.getActRepayAmt() == null
                            || finReim.getActRepayDate() == null) {
                        return RspVo.getFailureResponse(401, "财务还款情况不能为空");
                    }
                    RspVo rspVo = financeReimbursementService.modifyFinInfo(finReim, vo, processId);
                    if (!rspVo.isSuccess()) return rspVo;
                    break;
                }
            }
        }
        capProcessManageService.auditProject(finReim.getId(), processId, status, auditMsg);
        return RspVo.getSuccessResponse();
    }

    /**
     * 编辑融资还款
     * @param bodyStr json数据
     * @param submitType 0=保存，1=提交
     * @return
     */
    @RequestMapping("/edit")
    public @ResponseBody RspVo edit(String bodyStr, Integer submitType) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String str = StringEscapeUtils.unescapeJava(bodyStr);
        FinReimJsonVo finReimJson = JSON.parseObject(str, FinReimJsonVo.class);
        FinReimDto finReimDto = finReimJson.getInfo();

        //更新附件表-MKT_PROJECT_ATTACHMENT
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(finReimJson.getFileAtt()!=null){
            String[] fileAtt = finReimJson.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(vo, finReimDto.getId(), file);
                attachmentList.add(attachment);
            }
        }
        RspVo rspVo = financeReimbursementService.edit(finReimDto, finReimJson.getDetailList(), attachmentList, submitType, vo);
        return rspVo;
    }
}
